package cn.wzvtcsoft.sys.security.rbac.service;

import cn.wzvtcsoft.sys.entity.User;
import cn.wzvtcsoft.sys.security.BosUserDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.Set;

/**
 * @author swxu_2005@163.com
 */
@Component("rbacService")
public class RbacServiceImpl {

  @Autowired
  private SecurityServiceImpl securityService;

  private AntPathMatcher antPathMatcher = new AntPathMatcher();

  public boolean hasPermission(HttpServletRequest request, Authentication authentication) {
    Object principal = authentication.getPrincipal();
    String requestUrl = request.getRequestURI();
    boolean hasPermission = false;
    if (principal instanceof BosUserDetails) {
      User currUser = ((BosUserDetails) principal).getUser();
      Set<String> authorizedUrls = securityService.getAuthorizedUrls(currUser.getId());

      for (String url : authorizedUrls) {
        if (antPathMatcher.match(url, requestUrl)) {
          hasPermission = true;
          break;
        }
      }
    }
    return hasPermission;
  }

}
